package server;

import java.net.*;
import java.util.*;
import java.io.*;
import util.*;


public class Server extends ConsoleInputHandler{
	
	private static ServerSocket serverSocket;
	private static ArrayList<ServerSocketThread> currentConnections = new ArrayList<ServerSocketThread>();

	private static ConsoleInputHandler consoleInputHandler = new PrivateConsoleInputHandler();
	
	private static ConsoleUI console = new ConsoleUI("Server",consoleInputHandler);
	
	/**
	 * Start the server.
	 * @param args if --port and a number is found, the number will be used as the port.
	 */
	public static void main(String[] args){
		
		int port = 6125; // default port
        /* See if the argument -port portNumber is provided. */
        for (int i = 0; i<args.length;i++){
            if (args[i].equalsIgnoreCase("--port") && i<args.length-1){
            	try {
            		port = Integer.parseInt(args[i+1]);
            	} catch (NumberFormatException e){
            		System.out.println("--port argument found, but no/invalid number provided. Using default ("+port+").");
            		console.println("--port argument found, but no/invalid number provided. Using default ("+port+").");
            	}
                break;
            }
        }
		
		try {
			serverSocket = new ServerSocket(port); 
			console.println("Server is now started on the port "+ port+ ".");
			try {
				while (true) {
					try {
						ServerSocketThread socketThread = new ServerSocketThread(serverSocket.accept());
						currentConnections.add(socketThread);
						socketThread.start();
					}  catch (UnsupportedEncodingException e) {
						// OS doens't support UTF-8? This machine shouldn't even be running.
						e.printStackTrace();
						Server.consolePrint("Server or client doesn't support UTF-8.");
						
					} catch (IOException e) {
						e.printStackTrace();
						// server shouldn't terminate because of one bad connection
						// We therefore catch this exception "twice".
					}
				}
			} finally {
				serverSocket.close();
			}
			
		} catch (BindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void removeConnection(ServerSocketThread socketThread){
		Server.consolePrint("Server.removeConnection()");
		if (socketThread != null) {
			Game.removeUser(socketThread.getUsername());
			
			synchronized (currentConnections){
					currentConnections.remove(socketThread);
			}
		}
	}
	
	public static synchronized void consolePrint(String string){
		if (string != null){
			console.println(string);
			System.out.println(string);
		}
	}
	
	private static class PrivateConsoleInputHandler extends ConsoleInputHandler {
		
		public void processConsoleInput(String str) {
			// processUserInput(str);
			// Server doesn't respond to input
			
		}
	}
}
